<template>
  <div class="caregiver-management">
    <!-- 搜索和操作区域 -->
    <el-card shadow="never" class="search-card">
      <div class="search-container">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="护工姓名" class="search-item">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入护工姓名"
              clearable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item class="search-item">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-button 
          type="primary" 
          @click="handleAdd" 
          class="add-button"
        >
          <el-icon><Plus /></el-icon>新增护工
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <!-- 表格列保持不变 -->
        <el-table-column prop="caregiverId" label="护工ID" width="120" align="center" />
        <el-table-column label="护工姓名" width="120" align="center">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row.caregiverId)">
              {{ row.employee?.name || '-' }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="qualificationLevel" label="资质等级" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.qualificationLevel)">
              {{ getLevelName(row.qualificationLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specialty" label="专长领域" min-width="150" show-overflow-tooltip />
        <el-table-column prop="trainedElderCount" label="护理老人数量" width="120" align="center" />
        <el-table-column prop="experienceYears" label="工作经验(年)" width="120" align="center" />
        <el-table-column prop="evaluationScore" label="综合评分" width="170" align="center">
          <template #default="{ row }">
            <el-rate v-model="row.evaluationScore" disabled show-score :max="5" />
          </template>
        </el-table-column>
        <el-table-column prop="lastTrainingDate" label="最近培训日期" width="150" align="center">
          <template #default="{ row }">
            {{ formatSimpleDate(row.lastTrainingDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row.caregiverId)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.caregiverId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
   <el-dialog 
    v-model="editDialogVisible" 
    title="编辑护工信息" 
    width="50%"
    @close="resetEditForm"
  >
    <el-form 
      ref="editFormRef"
      :model="editForm" 
      label-width="120px"
      :rules="editFormRules"
    >
      <el-form-item label="护工姓名" >
        <el-input v-model="editForm.name" readonly/>
      </el-form-item>
      
      <el-form-item label="资质等级" prop="qualificationLevel">
        <el-select v-model="editForm.qualificationLevel">
          <el-option
            v-for="level in qualificationLevelOptions"
            :key="level.value"
            :label="level.label"
            :value="level.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="专长领域" prop="specialty">
        <el-input v-model="editForm.specialty" />
      </el-form-item>
      
      <el-form-item label="工作经验(年)" prop="experienceYears">
        <el-input-number 
          v-model="editForm.experienceYears" 
          :min="0" 
          :max="50"
        />
      </el-form-item>
      
      <el-form-item label="护理老人数量" prop="trainedElderCount">
        <el-input-number 
          v-model="editForm.trainedElderCount" 
          :min="0"
        />
      </el-form-item>
      
      <el-form-item label="综合评分" prop="evaluationScore">
        <el-rate v-model="editForm.evaluationScore" :max="5" />
      </el-form-item>
      
      <el-form-item label="最近培训日期" prop="lastTrainingDate">
        <el-date-picker
          v-model="editForm.lastTrainingDate"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditForm">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { page, deleteById,save,findById } from '@/api/caregiver'
import { useRouter } from 'vue-router'

// 获取路由实例
const router = useRouter()
// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 资质等级选项
const qualificationLevelOptions = [
  { value: 1, label: '初级' },
  { value: 2, label: '中级' },
  { value: 3, label: '高级' },
  { value: 4, label: '专家' }
]

// 获取资质等级名称
const getLevelName = (level) => {
  const item = qualificationLevelOptions.find(item => item.value === level)
  return item ? item.label : '-'
}

// 获取资质等级标签类型
const getLevelTagType = (level) => {
  const types = ['', 'success', 'warning', 'danger']
  return types[level] || ''
}

// 获取护工列表
const fetchCaregiverList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNo: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: searchForm.name,
    };
    const res = await page(params);
    tableData.value = res.records || res.data?.records || [];
    pagination.total = res.total || res.data?.total || 0;
    
    if (res.size) pagination.pageSize = res.size;
    if (res.current) pagination.currentPage = res.current;
    
  } catch (error) {
    console.error('获取护工列表失败:', error);
    ElMessage.error('获取护工列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchCaregiverList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchCaregiverList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchCaregiverList()
}

// 新增护工
const handleAdd = () => {
  router.push('/employer/save') // 跳转到护工新增页面
}

// 查看护工详情
const handleView = (id) => {
  console.log('查看护工详情:', id)
}

// 删除护工
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该护工吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteById(id)
      ElMessage.success('删除成功')
      fetchCaregiverList()
    } catch (error) {
      console.error('删除护工失败:', error)
    }
  }).catch(() => {})
}

// 简单的日期格式化方法
const formatSimpleDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toISOString().split('T')[0];
};
// 新增的编辑对话框相关状态
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
  caregiverId: null,
  name: '',
  qualificationLevel: 1,
  specialty: '',
  experienceYears: 0,
  trainedElderCount: 0,
  evaluationScore: 0,
  lastTrainingDate: ''
})

// 编辑表单验证规则
const editFormRules = {
  name: [{ required: true, message: '请输入护工姓名', trigger: 'blur' }],
  qualificationLevel: [{ required: true, message: '请选择资质等级', trigger: 'change' }],
  experienceYears: [{ required: true, message: '请输入工作经验', trigger: 'blur' }]
}

// 修改编辑按钮处理函数
const handleEdit = async (id) => {
  try {
    const res = await findById(id)
    Object.assign(editForm, {
      caregiverId: id,
      name: res.data.employee?.name || '',
      ...res.data
    })
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取护工信息失败:', error)
    ElMessage.error('获取护工信息失败')
  }
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    await save(editForm)
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    fetchCaregiverList()
  } catch (error) {
    if (!error.response) {
      // 验证失败不显示错误消息
      return
    }
    console.error('修改护工信息失败:', error)
    ElMessage.error('修改护工信息失败')
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value?.resetFields()
}
// 初始化
onMounted(() => {
  fetchCaregiverList()
})
</script>

<style scoped>
/* 整体布局 */
.caregiver-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

/* 搜索卡片美化 */
.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-grow: 1;
}

.search-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮美化 */
.add-button {
  margin-left: 16px;
  height: 36px;
  padding: 0 20px;
  border-radius: 8px;
  font-weight: 500;
  box-shadow: 0 2px 6px 0 rgba(64, 158, 255, 0.2);
  transition: all 0.3s;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px 0 rgba(64, 158, 255, 0.3);
}

.el-button {
  border-radius: 8px;
  padding: 8px 16px;
  transition: all 0.2s;
}

.el-button--primary {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  border: none;
}

/* 表格卡片美化 */
.table-card {
  border-radius: 12px;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: none;
  overflow: hidden;
}

/* 表格美化 */
.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f8fafc;
  --el-table-row-hover-bg-color: #f5f7fa;
  font-size: 14px;
}

.el-table :deep(th) {
  font-weight: 600;
  color: #303133;
  background-color: #f8fafc !important;
}

.el-table :deep(.el-table__row) {
  transition: background-color 0.2s;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

/* 标签美化 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

/* 分页美化 */
.pagination-wrapper {
  margin-top: 0;
  padding: 16px 20px;
  background-color: #f8fafc;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 12px 12px;
}

/* 对话框美化 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 16px 20px;
  background-color: #f8fafc;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  background-color: #f8fafc;
  border-top: 1px solid #ebeef5;
}

/* 评分组件美化 */
.el-rate {
  --el-rate-icon-size: 18px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form {
    flex-wrap: wrap;
  }
  
  .search-item {
    margin-right: 0;
    margin-bottom: 12px;
    width: 100%;
  }
  
  .search-item :deep(.el-input) {
    width: 100% !important;
  }
  
  .add-button {
    margin: 12px 0 0 0;
    width: 100%;
  }
  
  .el-table :deep(.el-table__cell) {
    padding: 8px 0;
  }
}
</style>